package com.gitee.cirnochat.notification.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.cirnochat.common.utils.RedissonLockUtil;
import com.gitee.cirnochat.notification.mapper.ExpoPushTokenMapper;
import com.gitee.cirnochat.notification.model.entity.ExpoPushToken;
import com.gitee.cirnochat.notification.service.ExpoPushTokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import static com.gitee.cirnochat.common.constant.RedisKey.EXPO_PUSH_TOKEN_LOCK_KEY;

/**
* @author FlanChan
* @description 针对表【expo_push_token(Expo推送令牌表)】的数据库操作Service实现
* @createDate 2025-05-28 22:35:14
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class ExpoPushTokenServiceImpl extends ServiceImpl<ExpoPushTokenMapper, ExpoPushToken>
    implements ExpoPushTokenService {
    private final RedissonLockUtil redissonLockUtil;

    @Override
    public void setExpoPushToken(String expoToken, String deviceId, Long userId) {
        // 根据deviceId和userId进行token查询
        ExpoPushToken token = this.getExpoPushTokenByDeviceIdAndUserId(deviceId, userId);
        if (token == null) {
            redissonLockUtil.redissonDistributedLocks(EXPO_PUSH_TOKEN_LOCK_KEY + deviceId, () -> {
                ExpoPushToken againToken = this.getOne(new LambdaQueryWrapper<>(ExpoPushToken.class)
                        .eq(ExpoPushToken::getDeviceId, deviceId)
                        .eq(ExpoPushToken::getUserId, userId));
                if (againToken == null) {
                    ExpoPushToken expoPushToken = new ExpoPushToken();
                    expoPushToken.setUserId(userId);
                    expoPushToken.setDeviceId(deviceId);
                    expoPushToken.setToken(expoToken);
                    this.save(expoPushToken);
                }
            });
        }

    }

    @Override
    public Boolean checkExpoPushToken(String deviceId, Long userId) {
        return this.exists(new LambdaQueryWrapper<>(ExpoPushToken.class)
                .eq(ExpoPushToken::getDeviceId, deviceId)
                .eq(ExpoPushToken::getUserId, userId));
    }


    @Override
    public ExpoPushToken getExpoPushTokenByDeviceIdAndUserId(String deviceId, Long userId) {
        return this.getOne(new LambdaQueryWrapper<>(ExpoPushToken.class)
                .eq(ExpoPushToken::getDeviceId, deviceId)
                .eq(ExpoPushToken::getUserId, userId));
    }
}




